package org.tong.database.jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;
import org.tong.bean.Student;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class StudentTemplateDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    public List<Student> queryAllStudents() {
        return jdbcTemplate.query("select * from student", new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet resultSet, int i) throws SQLException {
                Student student = new Student();
                student.setId(resultSet.getInt(1));
                student.setName(resultSet.getString(2));
                return student;
            }
        });
    }

    public int insert(Student student) {
        Assert.notNull(student.getName(), "student.name can be null");
        return jdbcTemplate.update("insert into student(name)values(?)", student.getName());
    }


}
